package handler

import (
	"encoding/json"
	"olefin-manage/cache"
	"olefin-manage/models"
	"olefin-manage/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "错误3次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "用户错误3次,禁止登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "用户登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "用户登录成功",
		"data": user,
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var article []models.Article
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(models.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  article,
		"total": total,
	})
	return
}
func CommitAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	commit := c.PostForm("commit")
	if title == "" || content == "" || commit == "" {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "不能为空",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Content: content,
		Commit:  commit,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "评论添加失败",
		})
		return
	}
	redis_key := "add_" + title
	var article models.Article
	models.DB.Where("title=?", title).Find(&article).Order(data)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "评论添加成功",
	})
	return
}
